import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

//import org.apache.commons.io.FileUtils;

public class AccountValue {
	/**
	 * @Fields PROPERTIES_NAME : 资源配置文件的名称
	 */
	private static String PROPERTIES_NAME = "jdbc";

	private static PropertyResourceBundle properTyResourceBundle;
	static {
		properTyResourceBundle = (PropertyResourceBundle) ResourceBundle.getBundle(PROPERTIES_NAME);
	}
	/**
	 * 读取某个文件夹下的所有文件
	 */
	@SuppressWarnings({ "rawtypes" })
	public static boolean readfile(String filepath)
			throws FileNotFoundException, IOException {
		System.out.println("123123");
		try {    
			System.out.println("begin time:"+new Date());
			File file = new File(filepath);//获取文件目录
			if (!file.isDirectory()) {//判断是否存在
				System.out.println("文件");
				System.out.println("path=" + file.getPath());
				System.out.println("absolutepath=" + file.getAbsolutePath());
				System.out.println("name=" + file.getName());
			} else if (file.isDirectory()) {
				System.out.println("文件夹");
				String[] filelist = file.list();//获取目录下文件
				List<String> controllerlist = new ArrayList<String>();
				for (int i = 0; i < filelist.length; i++) {//遍历文件
					File readfile = new File(filepath + "\\" + filelist[i]);//读取文件并判断是否存在
					if (!readfile.isDirectory()) {
						System.out.println("path=" + readfile.getPath());
						System.out.println("absolutepath="
								+ readfile.getAbsolutePath());
						System.out.println("name=" + readfile.getName());
						String[] filenames = readfile.getName().split("\\.");//拆分文件名获取发送来的日期
						if(readfile.getName().substring(0, 9).equals("163.VALUE") && filenames[filenames.length-1].equals("txt")){//判断文件名是否是网易的投连价值
							DBConnection connection = new DBConnection();//数据连接
							String selecthistorysql  = "select POLICY_NO,EARNINGS from wy_policy_history_accountvalue " +
									"where CODE_TYPE = '"+properTyResourceBundle.getString("codeType")+"' and " +
									"AGENT_COM = '"+properTyResourceBundle.getString("agentCom")+"' " +
									"and TO_CHAR(history_earnings_date,'yyyymmdd') = '"+filenames[2]+"'";
							System.out.println(selecthistorysql);
							List historylist = null;
							try {
								historylist = connection.queryForList(selecthistorysql);//查看该日期下是否已重复发送过账户价值
							} catch (SQLException e2) {
								e2.printStackTrace();
							}
							if(historylist != null && historylist.size() > 0){//如已发送过删除该日的历史记录，以便导入新数据
								String deletesql  = "delete from wy_policy_history_accountvalue " +
									"where CODE_TYPE = '"+properTyResourceBundle.getString("codeType")+"' and " +
									"AGENT_COM = '"+properTyResourceBundle.getString("agentCom")+"' " +
									"and TO_CHAR(history_earnings_date,'yyyymmdd') = '"+filenames[2]+"'";
								System.out.println(deletesql);
								try {
									if(connection.controllerTable(deletesql)){
										System.out.println("删除日期"+filenames[2]+"成功");
									}
								} catch (SQLException e1) {
									e1.printStackTrace();
								}
							}
							InputStream is = null;
							BufferedReader br = null;
							is = new FileInputStream(new File(readfile.getPath()));
							br = new BufferedReader(new InputStreamReader(is, "UTF-8"));//读取文件内容
							String line = "";
//							List insertcountlist = new ArrayList();
							while ((line = br.readLine()) != null) {
								String[] arr = line.split(",");//逗号拆分文件内容
								String earnting = arr[6];
								Double earn = Double.parseDouble(earnting);
								String accountValue = arr[5];
								Double accountV = Double.parseDouble(accountValue);
								DecimalFormat format = new DecimalFormat("0.00");
								earnting = format.format(earn);//获取账户价值保留两位小数
								accountValue = format.format(accountV);//获取账户价值保留两位小数
								String sql  = "insert into wy_policy_history_accountvalue " +
								"(ID,POLICY_NO,STATUS,MODIFIED_DATE,ACCOUNT_VALUE,EARNINGS,REMARK,AGENT_COM,START_DATE,CODE_TYPE,history_earnings_date)" +
								"values(seq_history_accountvalue.nextval,'"+arr[0]+"','"+arr[3]+"'," +
								"sysdate,'"+accountValue+"','"+earnting+"','','"+properTyResourceBundle.getString("agentCom")+"'," +
								"to_date('"+arr[2]+"','yyyy-mm-dd hh24:mi:ss'),'"+properTyResourceBundle.getString("codeType")+"'," +
								"to_date('"+arr[4]+"','yyyy-mm-dd hh24:mi:ss'))";
//								System.out.println(sql);
								controllerlist.add(sql);
//								connection.controllerTable(sql);//插入近历史表文件内容
//								String selectSql = "select POLICY_NO,COUNT_EARNINGS,EARNINGS_DATE from wy_policy_count_accountvalue " +
//								"where POLICY_NO = '"+arr[0]+"'";//判断是否为总收益表新保单
//								List list = connection.queryForList(selectSql);
//								String earnting = arr[6];
//								Double earn = Double.parseDouble(earnting);
//								DecimalFormat format = new DecimalFormat("0.00");
//								earn = Double.parseDouble(format.format(earn));//获取收益数据保留两位小数
//								if(list.size() == 0){//不存在总收益表中为新单，进行插入
//									String accountValue = arr[5];
//									Double accountV = Double.parseDouble(accountValue);
//									accountV = Double.parseDouble(format.format(accountV));//获取账户价值保留两位小数
//									String addsql  = "insert into wy_policy_count_accountvalue " +
//									"(ID,POLICY_NO,STATUS,EARNINGS_DATE,COUNT_EARNINGS,START_DATE,APPLY_DATE)" +
//									"values(SEQ_WY_POLICY_COUNT.nextval,'"+arr[0]+"','"+arr[3]+"'," +
//									"to_date('"+arr[4]+"','yyyy-mm-dd hh24:mi:ss'),'"+format.format(accountV+earn)+"'," +
//									"to_date('"+arr[2]+"','yyyy-mm-dd hh24:mi:ss'),null)";
//									System.out.println(addsql);
//									controllerlist.add(addsql);
////									connection.controllerTable(addsql);//将收益和账户价值之和插入到总收益表中
//								}else{
//									String oldEarn = "0.00";
//									if(historylist != null && historylist.size() > 0){
//										for (int j = 0; j < historylist.size(); j++) {
//											String policyNo = ((Map)historylist.get(j)).get("POLICY_NO").toString();
//											if(policyNo.equals(((Map)list.get(0)).get("POLICY_NO").toString())){
//												//获取该保单在传入日期下是否有原收益数据,如没有则为0
//												oldEarn = ((Map)historylist.get(j)).get("EARNINGS").toString();
//											}
//										}
//									}
//									Double oldear = 0.00;
//									oldear = Double.parseDouble(oldEarn);//转换原收益数据为Double
//									String countEarnings = ((Map)list.get(0)).get("COUNT_EARNINGS").toString();
//									Double countEarn = Double.parseDouble(countEarnings);
//									countEarn = Double.parseDouble(format.format(countEarn));//获取原总收益数据保留两位小数
//									String earningDate = ((Map)list.get(0)).get("EARNINGS_DATE").toString();//获取最新收益日期
//									Date earningDt = new SimpleDateFormat("yyyyMMdd").parse(earningDate);//获取该保单保存的最近一次收益日期
//									Date updateDate = new SimpleDateFormat("yyyyMMdd").parse(filenames[2]);//获取该保单传入的日期
//									String updatesql  = "update wy_policy_count_accountvalue set " +
//									"COUNT_EARNINGS = '" + format.format(countEarn - oldear + earn) +"' ";
//									if(earningDt.before(updateDate) || earningDt.equals(updateDate)){//判断最近一次收益日期是否小于等于本次的传入日期
//										//小于等于时需更新全部数据，否则为修补以前的错误数据只更新总收益价值
//										updatesql +=",STATUS ='"+arr[3]+"',EARNINGS_DATE = "+
//										"to_date('"+filenames[2]+"','yyyy-mm-dd hh24:mi:ss') ," +
//										"START_DATE = to_date('"+arr[2]+"','yyyy-mm-dd hh24:mi:ss') ";
//									}
//									updatesql += " where POLICY_NO = '"+arr[0]+"'";
//									System.out.println(updatesql);
//									controllerlist.add(updatesql);
////									connection.controllerTable(updatesql);//更新总收益表
//								}
							}
							connection.controllerTable(controllerlist);
							System.out.println("插入"+readfile.getName()+"完毕"+new Date());
							controllerlist = new ArrayList<String>();
							
							
							br.close();
							is.close();
							File target = new File(filepath+"/old."+readfile.getName());//生成新的文件
							for (int j= 1;target.exists();j++) {
								target = new File(filepath+"/old"+j+"."+readfile.getName());//判断改文件是否已存在如存在则修改文件名从新生成
							}
							boolean t = readfile.renameTo(target);//进行文件重命名
							System.out.println(t);
							if(t) {
							  System.out.println(readfile.getName() +" -> "+ "old."+readfile.getName());  
							} else { //更名失败，则采取变相的更名方法  
//							    try{  
////							        FileUtils.copyFile(readfile, target); // 将旧文件拷贝给新文件  
//							        System.out.println(readfile.getName() +" -> "+ "old."+readfile.getName());  
//							        //清除旧文件  
//							        System.out.println(readfile.delete());
//							    } catch (IOException e) {  
//							       e.printStackTrace();
//							    }  
							} 
						}
					} else if (readfile.isDirectory()) {
						readfile(filepath + "\\" + filelist[i]);
					}
				}
				DBConnection connection = new DBConnection();//数据连接
				String deletesql = "delete from wy_policy_count_accountvalue ";
				String dropSequence = "drop sequence SEQ_COUNT_ACCOUNTVALUE";
				String createSequence = "create sequence SEQ_COUNT_ACCOUNTVALUE " +
						"minvalue 1 " +
						"maxvalue 999999999 " +
						"start with 1 " +
						"increment by 1 " +
						"cache 20";
				System.out.println(deletesql);
				System.out.println(dropSequence);
				System.out.println(createSequence);
				controllerlist.add(deletesql);
				controllerlist.add(dropSequence);
				controllerlist.add(createSequence);
				connection.controllerTable(controllerlist);
				String addsql  = "insert into wy_policy_count_accountvalue " +
				" (ID,POLICY_NO,EARNINGS_DATE,COUNT_EARNINGS,START_DATE,APPLY_DATE)" +
				" select SEQ_COUNT_ACCOUNTVALUE.nextval ID,t.POLICY_NO,t.EARNINGS_DATE," +
				" trim(to_char(t.COUNT_EARNINGS,'999999990.99')),t.START_DATE,t.APPLY_DATE from " +
				" (select POLICY_NO,max(MODIFIED_DATE) EARNINGS_DATE," +
				" to_number(sum(EARNINGS)) as COUNT_EARNINGS,START_DATE,null as APPLY_DATE" +
				" from wy_policy_history_accountvalue group by POLICY_NO,START_DATE) t";
				System.out.println(addsql);
				controllerlist.add(addsql);
				connection.controllerTable(controllerlist);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("readfile()   Exception:" + e.getMessage());
		}
		return true;
	}
	
	public static void main(String[] args) {
		try {
			File file = new File("D:\\qweqweqwe\\111\\222");
			file.mkdirs();
			file = new File("D:\\qweqweqwe\\111\\222\\1.txt");
			file.createNewFile();
//			DBConnection connection = new DBConnection();
//			String selectSql = "select POLICY_NO,COUNT_EARNINGS from wy_policy_count_accountvalue where POLICY_NO = '01W043533'";
//			List list = connection.queryForList(selectSql);
//			for (int i = 0; i < list.size(); i++) {
//				Map map = (Map)list.get(i);
//				System.out.println(map.get("POLICY_NO"));
//				System.out.println(map.get("COUNT_EARNINGS"));
//			}
//			Date earningDt = new SimpleDateFormat("yyyyMMdd").parse("20141119");
//			Date updateDate = new SimpleDateFormat("yyyyMMdd").parse("20141118");
//			if(earningDt.before(updateDate) || earningDt.equals(updateDate)){
//				System.out.println(1);
//			}
//			DBConnection connection = new DBConnection();//数据连接
//			String sql  = "insert into wy_policy_history_accountvalue " +
//			"(ID,POLICY_NO,STATUS,MODIFIED_DATE,ACCOUNT_VALUE,EARNINGS,REMARK,AGENT_COM,START_DATE,CODE_TYPE,history_earnings_date)" +
//			"values(seq_history_accountvalue.nextval,'1','1'," +
//			"to_date('2014-01-01','yyyy-mm-dd hh24:mi:ss'),'1','1','','"+properTyResourceBundle.getString("agentCom")+"'," +
//			"to_date('2014-01-01','yyyy-mm-dd hh24:mi:ss'),'"+properTyResourceBundle.getString("codeType")+"'," +
//			"to_date('2014-01-01','yyyy-mm-dd hh24:mi:ss'))";
//			System.out.println(sql);
//			List<String> controllerlist = new ArrayList<String>();
//			controllerlist.add(sql);connection.controllerTable(controllerlist);
//			String file = properTyResourceBundle.getString("filepath");
//			readfile(file);
//			DecimalFormat df = new DecimalFormat("0.00");
//			String accountValue = "2.00";
//			Double accountV = Double.parseDouble(accountValue);
//			accountV = Double.parseDouble(df.format(accountV));
//			String earnting = "3.00";
//			Double earn = Double.parseDouble(earnting);
//			earn = Double.parseDouble(df.format(earn));
//			System.out.println(df.format(earn+accountV));
//			Double earn = Double.parseDouble(earnting);
//			NumberFormat numberFormat = NumberFormat.getNumberInstance();
//			numberFormat.setMaximumFractionDigits(2);
//			earnting = numberFormat.format(earn);
//			System.out.println(earnting);
		}  catch (Exception ex) {
			ex.printStackTrace();
		}
		System.out.println("ok");
	}
}
